﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using visinia.SmartEngine;
using visinia.SmartEngine.Installer;

namespace visinia.web.admin.pages
{
    public partial class AdminManageModules : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<ModuleInstalled> modules = ModulesInstalledController.GetInstalledModules();
            List<ModuleData> packages = new List<ModuleData>();
            foreach (ModuleInstalled module in modules)
            {
                if (!packages.Exists(p => p.Package == module.Package))
                {
                    ModuleData data = new ModuleData();
                    data.Package = module.Package;
                    data.modules = modules.FindAll(p => p.Package == module.Package);
                    packages.Add(data);
                }
            }
            PackagesList.DataSource = packages;
            PackagesList.DataBind();
        }

        public class ModuleData
        {
            private string _Package;
            public string Package { get { return _Package; } set { _Package = value; } }
            public List<ModuleInstalled> modules = new List<ModuleInstalled>();
        }

        protected void PackagesList_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            Repeater ModulesList = (Repeater)e.Item.FindControl("ModulesList");
            if (ModulesList != null)
            {
                ModuleData data = (ModuleData)e.Item.DataItem;
                ModulesList.DataSource = data.modules;
                ModulesList.DataBind();
            }
        }

        public string GetIcon(string icon)
        {

            if (string.IsNullOrEmpty(icon))
                return WebRoots.GetAdminRoot + "Themes/_Common/images/blank.gif";
            else
                return WebRoots.GetModulesRoot + icon;
        }

        protected void ModulesList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "UnInstall")
            {
                int ModuleInstalledId = Convert.ToInt32(e.CommandArgument);
                InstallController.UnInstallModule(ModuleInstalledId);
                Response.Redirect(Request.RawUrl);
            }
        }
        protected void NEW_MODULE_Click(object sender, EventArgs e)
        {
            Response.Redirect(SystemMenu.CallPage("_Install", "Module"));
        }
    }
}
